package hc;

import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.map.IMap;
import com.hazelcast.spi.properties.ClusterProperty;
import netty.util.StartAndStop;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MapPutAndGet extends StartAndStop {

    private PerformanceAnalyze performanceAnalyze = new PerformanceAnalyze();

    private HazelcastInstance hz;

    public MapPutAndGet(String publicAddress, int port, String member) {
        Config config = new Config();
        config.getNetworkConfig().setPublicAddress(publicAddress).setPort(port);
        config.getNetworkConfig().getJoin().getTcpIpConfig()
                .addMember(member);
        config.setProperty(ClusterProperty.EVENT_THREAD_COUNT.getName(), "10");

        hz = Hazelcast.newHazelcastInstance(config);
    }

    public void start() {
        performanceAnalyze.start();

        IMap<Integer, Long> in = hz.getMap("in");
        IMap<Integer, Long> out = hz.getMap("out");

        ExecutorService executorService = Executors.newFixedThreadPool(2);

        executorService.submit(() -> {
            while (running) {
                in.put(9, System.nanoTime());
            }
        });
        executorService.submit(() -> {
            while (running) {
                Long time = out.get(9);

                if (time != null) {
                    performanceAnalyze.timeDelay((System.nanoTime() - time)/2);
                    performanceAnalyze.cpCounter();
                    performanceAnalyze.cpCounter();
                }
            }
        });

    }

}
